package org.example.school.common;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class Context {

    private static final ThreadLocal<Long> USER_ID_HOLDER = new ThreadLocal<>();

    /**
     * 从Session中获取用户ID，如果ThreadLocal中已有则直接返回
     */
    public static Long getId() {
        // 优先从ThreadLocal获取
        Long userId = USER_ID_HOLDER.get();
        if (userId != null) {
            return userId;
        }

        // ThreadLocal中没有则从Session获取
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            HttpSession session = request.getSession(false);
            if (session != null) {
                userId = (Long) session.getAttribute("userId");
                if (userId != null) {
                    // 同时设置到ThreadLocal中，提高后续访问效率
                    USER_ID_HOLDER.set(userId);
                    return userId;
                }
            }
        }
        return null;
    }

    /**
     * 设置用户ID到Session和ThreadLocal
     */
    public static void setId(Long id) {
        if (id == null) {
            return;
        }

        // 设置到ThreadLocal
        USER_ID_HOLDER.set(id);

        // 设置到Session
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            HttpSession session = request.getSession();
            session.setAttribute("userId", id);
        }
    }

    /**
     * 清理ThreadLocal中的用户ID，防止内存泄漏
     */
    public static void clear() {
        USER_ID_HOLDER.remove();
    }
}
